package cn.com.acca.ma.dao.impl;

import cn.com.acca.ma.dao.ModelStockAnalysisDao;
import cn.com.acca.ma.dao.ModelStockMonthAnalysisDao;
import cn.com.acca.ma.hibernate.util.HibernateUtil;
import cn.com.acca.ma.jdbctemplate.impl.WriteModelStockAnalysisByDateTransactionCallback;
import cn.com.acca.ma.jdbctemplate.impl.WriteModelStockMonthAnalysisByDateTransactionCallback;
import cn.com.acca.ma.jdbctemplate.util.JdbcTemplateUtil;
import cn.com.acca.ma.model.ModelStockAnalysis;
import cn.com.acca.ma.model.ModelStockMonthAnalysis;
import cn.com.acca.ma.model.ModelTopStock;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class ModelStockMonthAnalysisDaoImpl extends BaseDaoImpl<ModelStockMonthAnalysis> implements
    ModelStockMonthAnalysisDao {

    public ModelStockMonthAnalysisDaoImpl() {
        super();
    }

    /**
     * 计算model_stock_month_analysis表的全部数据
     */
    @Override
    public void writeModelStockMonthAnalysis() {
        logger.info("开始计算model_stock_month_analysis表的全部数据");

        transactionTemplate = JdbcTemplateUtil.getTransactionTemplate();
        jdbcTemplate = JdbcTemplateUtil.getJdbcTemplate();

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                try {
                    jdbcTemplate
                        .execute("{call PKG_MODEL_STOCK_ANALYSIS.write_mdl_stock_month_analysis}");
                } catch (Throwable e) {
                    transactionStatus.setRollbackOnly();
                    // transactionStatus.rollbackToSavepoint(savepoint);
                }
                return null;
            }
        });
    }

    /**
     * 根据开始时间beginDate和结束时间endDate，从表MDL_STOCK_MONTH_ANALYSIS中获取END_DATE字段
     * @param beginDate
     * @param endDate
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Date> getDateByCondition(String beginDate, String endDate){
        logger.info("根据开始时间【" + beginDate + "】和结束时间【" + endDate + "】，"
            + "从表MDL_STOCK_MONTH_ANALYSIS中获取END_DATE字段");

        StringBuffer hql = new StringBuffer("select distinct t.endDate from ModelStockMonthAnalysis t " +
            "where t.endDate between to_date(?,'yyyy-mm-dd') and to_date(?,'yyyy-mm-dd')");
        session = HibernateUtil.currentSession();
        session.beginTransaction();
        Query query = session.createQuery(hql.toString());
        query.setParameter(0, beginDate);
        query.setParameter(1, endDate);
        List<Date> list = query.list();
        session.getTransaction().commit();
        session.close();

        return list;
    }

    /**
     * 从表MDL_STOCK_MONTH_ANALYSIS中获取date日的所有ModelStockMonthAnalysis对象
     * @param date
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<ModelStockMonthAnalysis> getModelStockMonthAnalysisByDate(String date){
        logger.info("从表MDL_STOCK_MONTH_ANALYSIS中获取日期【" + date + "】的所有ModelStockMonthAnalysis对象");

        StringBuffer hql = new StringBuffer("select t from ModelStockMonthAnalysis t " +
            "where t.endDate=to_date(?,'yyyy-mm-dd') order by t.endDate asc");
        session = HibernateUtil.currentSession();
        session.beginTransaction();
        Query query = session.createQuery(hql.toString());
        query.setParameter(0, date);
        List<ModelStockMonthAnalysis> list=query.list();
        session.getTransaction().commit();
        session.close();

        return list;
    }

    /**
     * 计算model_stock_month_analysis表的某一日的数据
     * @param multithreading
     * @param beginDate
     * @param endDate
     */
    @Override
    public void writeModelStockMonthAnalysisByDate(boolean multithreading, String beginDate, String endDate) {
        logger.info("开始计算model_stock_month_analysis表在某段时间内【" + beginDate + "】和【" + endDate + "】的数据");

        TransactionTemplate newTransactionTemplate = null;
        JdbcTemplate newJdbcTemplate = null;
        if (multithreading) {
            newTransactionTemplate = JdbcTemplateUtil.newTransactionTemplate();
            newJdbcTemplate = JdbcTemplateUtil.newJdbcTemplate();
            WriteModelStockMonthAnalysisByDateTransactionCallback writeModelStockMonthAnalysisByDateTransactionCallback = new WriteModelStockMonthAnalysisByDateTransactionCallback(newJdbcTemplate, beginDate, endDate);
            newTransactionTemplate.execute(writeModelStockMonthAnalysisByDateTransactionCallback);
        } else {
            transactionTemplate = JdbcTemplateUtil.getTransactionTemplate();
            jdbcTemplate = JdbcTemplateUtil.getJdbcTemplate();
            WriteModelStockMonthAnalysisByDateTransactionCallback writeModelStockMonthAnalysisByDateTransactionCallback = new WriteModelStockMonthAnalysisByDateTransactionCallback(jdbcTemplate, beginDate, endDate);
            transactionTemplate.execute(writeModelStockMonthAnalysisByDateTransactionCallback);
        }
    }

    /**
     * 根据开始日期和结束日期，查找中间的日期，并去重
     * @param beginDate
     * @param endDate
     * @return
     */
//    @Override
//    public List<String> findDistinctDateBetweenBeginDateAndEndDate(boolean multithreading, String beginDate,
//        String endDate) {
//        logger.info("根据开始日期【" + beginDate + "】和结束日期【" + endDate + "】，查找中间的日期，并去重");
//
//        String sql = "select distinct b.date_ from ( "
//            + "select to_char(t.date_, 'yyyymmdd') date_ from mdl_stock_analysis t "
//            + "where t.date_ between to_date(:beginDate,'yyyy-mm-dd') and to_date(:endDate,'yyyy-mm-dd') order by t.date_ asc) b "
//            + "order by b.date_ asc";
//        Map map = new HashMap();
//        map.put("beginDate", beginDate);
//        map.put("endDate", endDate);
//
//        if (multithreading) {
//            NamedParameterJdbcTemplate newNamedParameterJdbcTemplate = JdbcTemplateUtil.newNamedParameterJdbcTemplate();
//            TransactionTemplate newTransactionTemplate = JdbcTemplateUtil.newTransactionTemplate();
//            return (List<String>) newTransactionTemplate.execute(new TransactionCallback<Object>() {
//                @Override
//                public List<String> doInTransaction(TransactionStatus transactionStatus) {
//                    try {
//                        return newNamedParameterJdbcTemplate.queryForList(sql, map, String.class);
//                    } catch (Throwable e) {
//                        e.printStackTrace();
//                        transactionStatus.setRollbackOnly();
//                        // transactionStatus.rollbackToSavepoint(savepoint);
//                    }
//                    return null;
//                }
//            });
//        } else {
//            namedParameterJdbcTemplate = JdbcTemplateUtil.getNamedParameterJdbcTemplate();
//            transactionTemplate = JdbcTemplateUtil.getTransactionTemplate();
//            return (List<String>) transactionTemplate.execute(new TransactionCallback<Object>() {
//                @Override
//                public List<String> doInTransaction(TransactionStatus transactionStatus) {
//                    try {
//                        return namedParameterJdbcTemplate.queryForList(sql, map, String.class);
//                    } catch (Throwable e) {
//                        e.printStackTrace();
//                        transactionStatus.setRollbackOnly();
//                        // transactionStatus.rollbackToSavepoint(savepoint);
//                    }
//                    return null;
//                }
//            });
//        }
//    }

    /**
     * 向表MDL_STOCK_MONTH_ANALYSIS中插入ModelStockMonthAnalysis对象
     * @param modelStockMonthAnalysis
     */
    public void save(ModelStockMonthAnalysis modelStockMonthAnalysis){
        logger.info("向表MDL_STOCK_MONTH_ANALYSIS中插入ModelStockMonthAnalysis对象");

        session = HibernateUtil.currentSession();
        session.beginTransaction();
        session.persist(modelStockMonthAnalysis);
        session.getTransaction().commit();
        session.close();
    }
}
